﻿using System;
using System.Web.Mvc;
using CMSMVC4.Areas.Admin.Models;
using CMSMVC4.Filters;
using System.Linq;

namespace CMSMVC4.Areas.Admin.Controllers
{
    [Authorize(Roles = "Admin,New")]
    public class NewsController : Controller
    {
        readonly CMSMVC4Entities _db = new CMSMVC4Entities();
        CommandSql cm = new CommandSql();

        public ActionResult Sort()
        {
            ViewBag.M = new CommandSql().GetParrentByMenu("/Admin/News/Sort").Rows[0]["Parrent"];
            string curte = cm.GetLanguage();
            var data = _db.CateLangs.OrderByDescending(x => x.Category.Sort).Where(x => x.Category.Type == MenuType.TinTuc && x.LanguageCode.Equals(curte) && x.Category.Status == CategoriStatus.Thuong).ToList();
            return View(data);
        }

        //
        // GET: /Admin/News/ListNews
        #region
        public ActionResult ListNews()
        {
            ViewBag.M = new CommandSql().GetParrentByMenu("/Admin/News/ListNews").Rows[0]["Parrent"];
            var data = new CommandSql().GetAllNews();
            ViewBag.lang = new CommandSql().GetLanguage();

            return View(data);
        }
        #endregion


        //
        // GET: /Admin/News/AddNews
        #region Add
        [HttpGet]
        public ActionResult AddNews(string id)
        {
            ViewBag.M = new CommandSql().GetParrentByMenu("/Admin/News/AddNews").Rows[0]["Parrent"];
            //ckediter
            var a = _db.Categories.Where(x => x.Type == MenuType.TinTuc && x.Status == CategoriStatus.Thuong).ToList();
            ViewBag.Active = a.Count == 0 ? 0 : 1;
            var lang = new CommandSql().GetLanguage().Substring(0, 2);
            ViewBag.l = lang;
            ViewBag.lang = new CommandSql().GetLanguage();
            string str = ViewBag.lang;
            //------------combobox danh muc-----------------
            NewsModels model = new NewsModels();
            var cateN = _db.CateLangs.Where(x => x.Category.Type == MenuType.TinTuc && x.LanguageCode == str).ToList();
            model.Listdata = new SelectList(cateN, "CategoriesId", "Name");

            Page pagenhap;
            if (cateN.Count > 0)
            {
                int pageid;
                if (int.TryParse(id, out pageid))//neu dung la sua?
                {
                    pagenhap = _db.Pages.FirstOrDefault(x => x.Id == pageid);
                    if (pagenhap == null) //neu ko co nhap
                    {
                        return View("Error");
                    }
                }
                else//them moi
                {
                    int n = cateN[0].CategoriesId;
                    pagenhap = _db.Pages.FirstOrDefault(x => x.CategoriesID == n && x.Status == PageStatus.Nhap);
                    if (pagenhap == null) //neu ko co nhap
                    {
                        Page pn = new Page();
                        pn.CategoriesID = cateN[0].CategoriesId;
                        pn.Status = PageStatus.Nhap;
                        pn.View = 0;
                        pn.Tab = 1;
                        pn.Date = DateTime.Now;
                        _db.Pages.AddObject(pn);
                        _db.SaveChanges();
                        pagenhap = _db.Pages.FirstOrDefault(x => x.CategoriesID == n && x.Status == PageStatus.Nhap);
                    }
                }
                var pagelangv =
                        _db.PageLangs.FirstOrDefault(x => x.PageId == pagenhap.Id && x.LanguageCode.Equals("vi-vn"));
                var pagelange =
                    _db.PageLangs.FirstOrDefault(x => x.PageId == pagenhap.Id && x.LanguageCode.Equals("en-us"));
                if (pagelangv == null)
                {
                    PageLang pl = new PageLang();
                    pl.PageId = pagenhap.Id;
                    pl.LanguageCode = "vi-vn";
                    pl.Name = "Tin Tức";
                    _db.PageLangs.AddObject(pl);
                    _db.SaveChanges();
                    pagelangv =
                    _db.PageLangs.FirstOrDefault(x => x.PageId == pagenhap.Id && x.LanguageCode.Equals("vi-vn"));
                }
                if (pagelange == null)
                {
                    PageLang pl = new PageLang();
                    pl.PageId = pagenhap.Id;
                    pl.LanguageCode = "en-us";
                    pl.Name = "News";
                    _db.PageLangs.AddObject(pl);
                    _db.SaveChanges();
                    pagelange =
                    _db.PageLangs.FirstOrDefault(x => x.PageId == pagenhap.Id && x.LanguageCode.Equals("en-us"));
                }
                model.CateId = pagenhap.CategoriesID;
                model.Pageid = pagenhap.Id;
                model.Pagelagvi = pagelangv.Id;
                model.Pagelagen = pagelange.Id;
                model.TitleVi = pagelangv.Name;
                model.TitleEn = pagelange.Name;
                model.ContentVi = pagelangv.FullContent;
                model.ContentEn = pagelange.FullContent;
                model.SumVi = pagelangv.Summary;
                model.SumEn = pagelange.Summary;
                model.Img = pagenhap.Img;
                return View(model);
            }
            return View("Error");//ko co danh muc nen khong the tao bai viet
        }

        [HttpPost]
        public ActionResult Addnews(NewsModels models)
        {
            if (ModelState.IsValid)
            {
                int ex = models.CateId;
                var page = _db.Pages.FirstOrDefault(x => x.Id == models.Pageid);
                if (page != null)
                {
                    page.CategoriesID = ex;
                    page.Status = PageStatus.Thuong;
                    page.Img = models.Img;
                    page.Date = DateTime.Now;
                    _db.SaveChanges();
                }
                var pagelegv = _db.PageLangs.FirstOrDefault(x => x.Id == models.Pagelagvi);
                if (pagelegv != null)
                {
                    pagelegv.FullContent = models.ContentVi;
                    pagelegv.Summary = models.SumVi;
                    pagelegv.Name = models.TitleVi;
                    _db.SaveChanges();
                }
                var pagelege = _db.PageLangs.FirstOrDefault(x => x.Id == models.Pagelagen);
                if (pagelege != null)
                {
                    pagelege.Name = models.TitleEn;
                    pagelege.FullContent = models.ContentEn;
                    pagelege.Summary = models.SumEn;
                    _db.SaveChanges();
                }
                ModelState.AddModelError("", "SuccessFull");
            }
            //string lang = new CommandSql().GetLanguage();
            //var cateN = _db.CateLangs.Where(x => x.Category.Type == MenuType.TinTuc && x.LanguageCode == lang).ToList();
            //models.listdata = new SelectList(cateN, "CategoriesId", "Name");
            return RedirectToAction("ListNews");
        }
        #endregion

        //
        // GET: /Admin/News/NewCategory
        #region
        [HttpGet]
        public ActionResult NewCategory()
        {
            return PartialView();
        }

        [HttpPost]
        public ActionResult NewCategory(CategoryNews models)
        {
            if (ModelState.IsValid)
            {
                int sort = 0;
                var catelast = _db.Categories.FirstOrDefault(x => x.Type == MenuType.TinTuc && x.Status == CategoriStatus.Thuong);
                if (catelast != null)
                {
                    if (catelast.Sort != null) sort += (int) catelast.Sort +1;
                }
                var c = new Category { Type = MenuType.TinTuc, Status = CategoriStatus.Thuong, Sort = sort };
                _db.Categories.AddObject(c);
                _db.SaveChanges();
                var cate = _db.Categories.OrderByDescending(x => x.Id).FirstOrDefault(x => x.Type == MenuType.TinTuc);
                var cateLangEn = new CateLang();
                if (cate != null) cateLangEn.CategoriesId = cate.Id;
                cateLangEn.Name = models.NameEn;
                cateLangEn.LanguageCode = "en-us";
                _db.CateLangs.AddObject(cateLangEn);

                var cateLangVi = new CateLang();
                if (cate != null) cateLangVi.CategoriesId = cate.Id;
                cateLangVi.Name = models.NameVi;
                cateLangVi.LanguageCode = "vi-vn";
                _db.CateLangs.AddObject(cateLangVi);

                _db.SaveChanges();


                if (Request.IsAjaxRequest())
                {
                    return JavaScript("window.location='/Admin/News/AddNews'");
                }
                return RedirectToAction("AddNews");
            }
            if (Request.IsAjaxRequest())
            {
                return PartialView(models);
            }
            return View(models);
        }
        #endregion

        //
        // GET: /Admin/News/Detail
        #region
        [HttpGet]
        public ActionResult Views()
        {
            return View();
        }
        #endregion

        //
        // GET: /Admin/News/Delete
        #region
        [HttpGet]
        public ActionResult Delete(int id)
        {
            return PartialView();
        }

        [HttpPost]
        public ActionResult Delete(string[] id)
        {
            if (id != null)
            {
                foreach (var i in id)
                {
                    int idcomment;
                    int.TryParse(i, out idcomment);
                    var row = _db.Pages.FirstOrDefault(x => x.Id == idcomment);
                    _db.Pages.DeleteObject(row);
                    _db.SaveChanges();
                }
            }
            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }
        #endregion

        //
        //GET: /Admin/News/DeleteCateGory
        #region
        [HttpGet]
        public ActionResult DeleteCate(int id)
        {
            //ViewBag.lang = new CommandSql().GetLanguage();
            //string str = ViewBag.lang;
            //var cateN = _db.CateLangs.Where(x => x.Category.Type == MenuType.TinTuc && x.LanguageCode == str).ToList();
            //ViewBag.Cate = new SelectList(cateN, "CategoriesId", "Name");
            Category c = _db.Categories.FirstOrDefault(x => x.Id == id);
            _db.Categories.DeleteObject(c);
            _db.SaveChanges();

            return Redirect(Request.UrlReferrer.ToString());
        }


        #endregion


        //
        //GET: /Admin/Active
        public ActionResult Active()
        {
            var data = _db.Categories.Where(x => x.Type == MenuType.TinTuc).ToList();
            if (data.Count > 0)
            {
                foreach (var c in data)
                {
                    c.Status = c.Status == 0 ? 1 : 0;
                }
            }
            _db.SaveChanges();
            return RedirectToAction("AddNews");
        }
    }
}
